<template>
  <div class="app-container-more app-container">
    <el-dialog :visible.sync="outerVisible" title="选择经纬度" width="50%; ">
      <div class="app-container">
        <el-autocomplete
          v-model="mapLocation.address"
          :fetch-suggestions="querySearch"
          :trigger-on-focus="false"
          placeholder="请输入详细地址"
          style="width: 100%"
          @select="handleSelect"
        />
        <div style="margin: 5px">
          <baidu-map :center="mapCenter"
                     :scroll-wheel-zoom="true"
                     :zoom="mapZoom"
                     ak="baidu-ak" class="bm-view" style="width: 100%; height:300px; z-index: 100"
                     @moveend="syncCenterAndZoom" @moving="syncCenterAndZoom" @ready="handlerBMap"
                     @zoomend="syncCenterAndZoom"/>
        </div>
      </div>
      <div slot="footer" class="dialog-footer tianjie_button">
        <el-button @click="outerVisible = false">取 消</el-button>
        <el-button type="primary" @click="outerVisible = false">确定</el-button>
      </div>
    </el-dialog>
    <el-form ref="form" :disabled="disableStus" :model="form" :rules="rules" class="clearfix" label-width="140px">
      <div class="content-left clearfix">
        <div class="title2"><span> </span>基本信息</div>
        <el-form-item label="企业名称" prop="epName">
          <el-input v-model="form.epName" placeholder="请输入企业名称"/>
        </el-form-item>
        <el-form-item label="区域选择" prop="epAddress">
          <el-row>
            <el-col>
              <div class="content-address">
                <div>
                  <el-select v-model="form.epProvince" class="adress-select"
                             placeholder="请选择省" @change="chooseProvince">
                    <el-option v-for="item in provinceData" :key="item.code"
                               :label="item.name" :value="item.code"></el-option>
                  </el-select>
                </div>
                <div>
                  <el-select v-model="form.epCity" class="adress-select"
                             placeholder="请选择市" @change="chooseCity">
                    <el-option v-for="item in cityData" :key="item.code"
                               :label="item.name" :value="item.code"></el-option>
                  </el-select>
                </div>
                <div>
                  <el-select v-model="form.epArea" class="adress-select"
                             placeholder="请选择区">
                    <el-option v-for="item in areaData" :key="item.code"
                               :label="item.name" :value="item.code"></el-option>
                  </el-select>
                </div>
              </div>
            </el-col>
          </el-row>


        </el-form-item>
        <el-form-item label="注册地址" prop="epArea">
          <el-input v-model="form.epAddress" placeholder="请输入注册地址"/>
        </el-form-item>
        <el-form-item label="企业法人" prop="epLegalPerson">
          <el-input v-model="form.epLegalPerson" placeholder="请输入企业法人"/>
        </el-form-item>
        <el-form-item label="企业联系电话" prop="epPhone">
          <el-input v-model="form.epPhone" placeholder="请输入企业联系电话"/>
        </el-form-item>
        <el-form-item label="企业邮箱" prop="epEmail">
          <el-input v-model="form.epEmail" placeholder="请输入企业邮箱"/>
        </el-form-item>
        <el-form-item label="经纬度" prop="epLg">
          <el-row>
            <el-col>
              <div class="weidu">
                <div style="width: 38%">

                  <el-input v-model="form.epLg" placeholder="请输入经度"/>
                </div>
                <div style="width: 38%">
                  <el-input v-model="form.epLt" placeholder="请输入纬度"/>
                </div>

                <div style="width: 20%; text-align: center;height: 36px;">
                  <el-button size="small" style="height: 34px;" type="primary">定位选择</el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="企业组织机构代码" prop="epOgCode">
          <el-input v-model="form.epOgCode" placeholder="请输入企业组织机构代码"/>
        </el-form-item>
        <el-form-item label="行业类型" prop="epIndustryCategory">
          <el-cascader
            ref="cascader"
            v-model="hangyeArr"
            :options="hangye"
            :props="{ checkStrictly: true }"
            clearable
            style="width: 100%"
            @change="handleAddressFun">
          </el-cascader>
        </el-form-item>
        <el-form-item label="企业规模" prop="epScale">
          <el-select v-model="qiyIndex" clearable placeholder="请选择" style="width: 100%;" @change="Qychangetype">
            <el-option v-for="item in qiyegm" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="污染类型" prop="epType">
          <el-row style="width: 100%;">
            <el-col>
              <div style="width: 100%;">
                <el-select v-model="wrValue" clearable placeholder="请选择" style="width: 100%;" @change="wrChange">
                  <el-option v-for="item in wrType" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
      </div>
      <div class="content-middle">
        <div class="title2">&nbsp;</div>
        <el-form-item label="企业曾用名" prop="epFormerName">
          <el-input v-model="form.epFormerName" placeholder="请输入企业曾用名"/>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="epCreditCode">
          <el-input v-model="form.epCreditCode" placeholder="请输入统一社会信用代码"/>
        </el-form-item>
        <el-form-item label="企业生产状态">
          <el-row style="width: 100%;">
            <el-col>
              <div style="width: 100%;">
                <el-select v-model="valuetype" clearable placeholder="请选择" style="width: 100%;" @change="changetype">
                  <el-option v-for="item in qiye" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <div class="title2"><span> </span>其他信息</div>
        <el-form-item label="企业环保监管级别" prop="epEnvLevel" style="padding-bottom: 10px; margin-top: 20px">
          <el-row style="width: 100%;">
            <el-col>
              <div style="width: 100%;">
                <el-select v-model="jgValue" clearable placeholder="请选择" style="width: 100%;" @change="jgChange">
                  <el-option v-for="item in jgType" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="企业环保负责人" prop="epEnvPeople">
          <el-input v-model="form.epEnvPeople" placeholder="请输入企业环保负责人"/>
        </el-form-item>
        <el-form-item label="企业环保负责人电话" prop="epEnvPhone">
          <el-input v-model="form.epEnvPhone" placeholder="请输入企业环保负责人联系电话"/>
        </el-form-item>
        <el-form-item label="投产日期" prop="epProductTime">
          <el-date-picker v-model="form.epProductTime" clearable
                          placeholder="选择投产日期"
                          size="small"
                          style="width: 100%"
                          type="date" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否注销">
          <el-row style="width: 100%;">
            <el-col>
              <div style="width: 100%;">
                <el-select v-model="zhuxiaoIndex" clearable placeholder="请选择" style="width: 100%;"
                           @change="cancellation">
                  <el-option v-for="item in zhuxiao" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="注册资本(万元)" prop="epRegisteredCapital">
          <el-input v-model="form.epRegisteredCapital" placeholder="请输入注册资本"  type="number"/>
        </el-form-item>
      </div>
      <div class="content-right">
        <div class="title2"><span></span>简介信息</div>
        <el-form-item label="企业简称" prop="epShortName">
          <el-input v-model="form.epShortName" placeholder="请输入企业简称"/>
        </el-form-item>
        <el-form-item label="企业logo" prop="epLogo" style="height: 168px">
          <el-row style=" width: 50%">
            <el-col>
              <div style="border: 1px solid #ccc; ">
                <div :disabled="disableStus">
                  <ImageUpload v-model="form.epLogo"/>
                </div>

              </div>
            </el-col>
          </el-row>
          <!--          <el-input v-model="form.epLogo" placeholder="请输入企业logo"  :rows="6"  type="textarea"  />-->
        </el-form-item>
        <el-form-item label="企业标签" prop="epLabel">
          <el-input v-model="form.epLabel" placeholder="请输入企业标签"/>
        </el-form-item>
        <el-form-item label="企业简介" prop="epIntroduction" style="margin-top:10px">
          <el-input v-model="form.epIntroduction" :rows="5" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
        <el-form-item label="企业官方网站" prop="epWebsite">
          <el-input v-model="form.epWebsite" placeholder="请输入企业官方网站"/>
        </el-form-item>
        <el-form-item label="企业生产经营地址" prop="epProductAddress">
          <el-input v-model="form.epProductAddress" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
import city from '@/assets/chinaCity.json'
import hangye from '@/assets/hangye.json'
import {addInfo, delInfo, exportInfo, getInfo, InfoItem, listInfo, updateInfo} from "@/api/enterprise/info";
import {isIntegerNotMust,validatePhoneTwo,validateIdNo,validateEMail} from "@/api/validate/validate";

export default {
  name: "Info",
  data() {
    const phoneRules = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入联系电话'))
      } else {
        const reg = /^1[3|4|5|6|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的电话'))
        }
      }
    }
    const emailRules = (rule, value, callback) =>{
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else {
        const reg = /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的邮箱'))
        }
      }
    }
    return {
      location: '北京',
      keyword: '宝鸡',
      hangye: hangye,
      hangyeArr: [],
      mapInfo: {
        province: "",
        city: "",
        area: "",
      },
      disableStus: false,
      areaStus: false,
      center: {
        lng: 107.234224,
        lat: 34.367723,
      },
      zoom: 15,
      ISstatus: true,
      innerVisible: true,
      outerVisible: false,
      mapZoom: 15,
      mapCenter: {lng: 0, lat: 0},
      mapLocation: {
        address: undefined,
        coordinate: undefined
      },
      formAddressData: {
        province: "",
        city: "",
        district: "",
        address: "",
      },
      provinceData: [],
      cityData: [],
      areaData: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      wrType: [
        {
          value: '0',
          label: '水污染'
        },
        {
          value: '1',
          label: '气污染'
        },
        {
          value: '2',
          label: '固体污染'
        },
        {
          value: '3',
          label: '噪声污染'
        },

      ],
      wrValue: '0',
      jgType: [
        {
          value: '0',
          label: '省控'
        },
        {
          value: '1',
          label: '国控'
        },
        {
          value: '2',
          label: '区控'
        },
        {
          value: '3',
          label: '地监'
        },

      ],
      jgValue: '3',
      qiye: [
        {
          value: '1',
          label: '生产'
        },
        {
          value: '0',
          label: '停产'
        },

      ],
      valuetype: '1',
      zhuxiao: [
        {
          value: '1',
          label: '是'
        },
        {
          value: '0',
          label: '否'
        },

      ],
      zhuxiaoIndex: '0',
      qiyegm: [
        {
          value: '0',
          label: '小型'
        },
        {
          value: '1',
          label: '中型'
        },
        {
          value: '2',
          label: '大型'
        },

      ],
      qiyIndex: '0',
      value: '1',
      // 企业基本信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        epName: null,
        epAddress: null,
        epProvince: null,
        epCity: null,
        epArea: null,
        epLegalPerson: null,
        epPhone: null,
        epEmail: null,
        epLg: null,
        epLt: null,
        epOgCode: null,
        epCreditCode: null,
        epIndustryCategory: null,
        epScale: null,
        epRegisteredCapital: null,
        epStatus: null,
        epEnvLevel: null,
        epEnvPeople: null,
        epEnvPhone: null,
        epProductTime: null,
        epLogoutStatus: null,
        epFormerName: null,
        epShortName: null,
        epLabel: null,
        epIntroduction: null,
        epWebsite: null,
        epProductAddress: null,
        epLogo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        epName: [
          {required: true, message: "企业名称不能为空", trigger: "blur"}
        ],
        epLegalPerson: [
          {required: true, message: "企业法人不能为空", trigger: "blur"}
        ],
        epCreditCode: [
          {required: true, message: "统一社会信用代码不能为空", trigger: "blur"}
        ],
        epPhone: [
          {validator:phoneRules, trigger: "blur"}
        ],
        epEnvPhone: [
          {validator:phoneRules, trigger: "blur"}
        ],
        epRegisteredCapital: [
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的格式,可保留两位小数' }
        ],
        epEmail: [
          {validator:emailRules, trigger: "blur"}
        ],
      }
    };
  },
  created() {
    // this.reset();
    this.changeAddressFromVisible();
  },
  mounted() {
       const userName=this.$route.query.userName
       this.getEpInfo(userName)
  },
  methods: {
    getEpInfo(userName) {
      var that=this;
      InfoItem(userName).then(res => {
        const arr = [];
        const arrPro = [];
        const arrCity = [];
        //如果有data
        if (res.hasOwnProperty("data")) {
          this.areaStus = true;
          this.form = res.data;
          if(this.form.remark){
            this.hangyeArr = this.form.remark.split(',');
          }

          // console.log(this.hangyeArr)
          this.mapInfo.province = that.form.epProvince
          this.mapInfo.city = that.form.epCity
          this.mapInfo.area = that.form.epArea
          for (var i = 0; i < that.provinceData.length; i++) {
            if (that.form.epProvince == city[i].code) {
              arr.push(city[i])
              that.form.epProvince = city[i].name
            }
          }
          for (var j = 0; j < arr[0].cityList.length; j++) {
            if (that.form.epCity == arr[0].cityList[j].code) {
              arrPro.push(arr[0].cityList[j]);
              that.form.epCity = arr[0].cityList[j].name
            }
          }
          for (var k = 0; k < arrPro[0].areaList.length; k++) {
            if (that.form.epArea == arrPro[0].areaList[k].code) {

              that.form.epArea = arrPro[0].areaList[k].name
            }
          }

          this.disableStus = true;

        }
        else {
          this.disableStus = false;
        }
      })
    },
    //编辑
    getEdit() {
      this.disableStus = !this.disableStus;
    },
    handleAddressFun(e, form, thsAreaCode) {
      this.hangyeArr = e;
      this.form.remark = this.hangyeArr.toString()

      if (e[0]) {
        this.form.epIndustryCategory = e[0]
      }
      if (e[1]) {
        this.form.epIndustryCategory = e[1]
      }
      if (e[2]) {
        this.form.epIndustryCategory = e[2]
      }
      let nodesObj = this.$refs['cascader'].getCheckedNodes()
    },
    //企业规模
    Qychangetype(e) {
      this.form.epScale = e
    },
    wrChange(e){
      this.form.epType = e
    },
    jgChange(e){
      this.form.epEnvLevel = e
    },
    /** 是否注销 */
    cancellation(e) {
      this.form.epLogoutStatus = e;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //打开地址编辑表单
    changeAddressFromVisible() {
      this.initAddressFrom(city)
    },
    // 选择省
    chooseProvince(value) {
      this.areaStus = false;
      if (value == '香港特别行政区') {
        this.selectCityDisabled = true
      } else {
        this.selectCityDisabled = false
      }
      this.cityData = [];
      this.areaData = [];
      this.form.epCity = '';
      this.form.epArea = '';
      this.provinceData.map(e => {
        if (value == e.code) {
          this.cityData = e.cityList;
          return;
        }
      })
      this.provinceData = this.provinceData;
    },
    // 选择市
    chooseCity(value) {
      this.form.epArea = '';
      this.cityData.map(e => {
        if (value == e.code) {
          this.areaData = e.areaList;
          return;
        }
      })
    },
    //初始化表单信息
    initAddressFrom(data) {
      this.provinceData = data;
      this.provinceData.map(e => {
        if (this.form.epProvince == e.code) {
          this.cityData = e.cityList;
        }
      })
      this.cityData.map(e => {
        if (this.form.epCity == e.code) {
          this.areaData = e.areaList;
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        epId: null,
        epName: null,
        epAddress: null,
        epProvince: null,
        epCity: null,
        epArea: null,
        epLegalPerson: null,
        epPhone: null,
        epEmail: null,
        epLg: null,
        epLt: null,
        epOgCode: null,
        epIndustryCategory: null,
        epScale: null,
        epRegisteredCapital: null,
        epStatus: '',
        epEnvLevel: null,
        epEnvPeople: null,
        epEnvPhone: null,
        epProductTime: null,
        epLogoutStatus: 0,
        epFormerName: null,
        epShortName: null,
        epLabel: null,
        epCreditCode:null,
        epIntroduction: null,
        epWebsite: null,
        epProductAddress: null,
        epLogo: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    syncCenterAndZoom(e) {
      const {lng, lat} = e.target.getCenter();
      this.form.epLg = lng
      this.form.epLt = lat
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.epId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业基本信息";
      this.upload.fileList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const epId = row.epId || this.ids
      getInfo(epId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业基本信息";
      });
      this.upload.fileList = [{name: this.form.fileName, url: this.form.filePath}];
    },
    /** 提交按钮 */
    submitForm() {

      if (this.areaStus) {
        // console.log(this.mapInfo)
        this.form.epProvince = this.mapInfo.province;
        this.form.epCity = this.mapInfo.city;
        this.form.epArea = this.mapInfo.area;
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.epId != null) {
            updateInfo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            addInfo(this.form).then(response => {
              this.msgSuccess("新增成功");
            });
          }
        }
      });
    },

    handlerBMap({BMap, map}) {
      this.BMap = BMap
      this.map = map
      if (this.mapLocation.coordinate && this.mapLocation.coordinate.lng) {
        this.mapCenter.lng = this.mapLocation.coordinate.lng
        this.mapCenter.lat = this.mapLocation.coordinate.lat
        // console.log(this.mapCenter.lng)
        this.mapZoom = 15
        map.addOverlay(new this.BMap.Marker(this.mapLocation.coordinate))
      } else {
        this.mapCenter.lng = 107.234224
        this.mapCenter.lat = 34.367723
        this.mapZoom = 10
      }
    },
    querySearch(queryString, cb) {
      var that = this
      var myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(queryString, function (point) {
        if (point) {
          that.mapLocation.coordinate = point
          that.makerCenter(point)
        } else {
          that.mapLocation.coordinate = null
        }
      }, this.locationCity)
      var options = {
        onSearchComplete: function (results) {
          if (local.getStatus() === 0) {
            // 判断状态是否正确
            var s = []
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              var x = results.getPoi(i)
              var item = {value: x.address + x.title, point: x.point}
              s.push(item)
              cb(s)
            }
          } else {
            cb()
          }
        }
      }
      var local = new this.BMap.LocalSearch(this.map, options)
      local.search(queryString)
    },
    handleSelect(item) {
      var {point} = item
      this.mapLocation.coordinate = point
      this.makerCenter(point)
    },
    makerCenter(point) {
      if (this.map) {
        this.map.clearOverlays()
        this.map.addOverlay(new this.BMap.Marker(point))
        this.mapCenter.lng = point.lng
        this.mapCenter.lat = point.lat
        this.mapZoom = 15
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企业基本信息数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportInfo(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    changetype(e) {
      this.form.epStatus = e;
      // console.log(e)
    },
  }
};
</script>

<style scoped>
.map {
  width: 500px;
  height: 500px;
}

.content-left {
  width: 30%;
  float: left;
}

.content-middle {
  width: 30%;
  float: left;
  margin-left: 3%;
}

.content-right {
  width: 30%;
  float: left;
  margin-left: 3%;
}

.content-address {
  display: flex;
  width: 100%;

}

.title2 {
  height: 40px;
  /*padding: 20px 0;*/

}

.title2 span {
  display: inline-block;
  border-radius: 50%;
  width: 15px;
  height: 15px;
  vertical-align: middle;
  margin-right: 10px;
  background-color: deepskyblue;
}

.app-container-more {
  padding-left: 60px;
  padding-right: 60px;
}

.clearfix:after {
  content: "020";
  display: block;
  height: 0;
  clear: both;
}

.weidu {
  display: flex;
}

.avatar-hide {
  display: none;
}

.avatar2:hover .avatar-hide {
  position: absolute;
  display: block;
  left: 0;
  font-size: 30px;
  color: #fff;
  z-index: 1000000000;
  top: 0;
  line-height: 178px;
  width: 100%;

  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.avatar-uploader {
  width: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-form-item {
  /* height: 80px; */
  margin-bottom: 35px;
  /*padding-bottom: 20px;*/
}

.el-form-item__label {
  text-align: left;
}

</style>
